/**
 *  判断是否为外部链接
 *
 * @param {string} path
 * @returns {Boolean}
 */
export function isExternal(path: string) {
  return /^(https?:|http?:|mailto:|tel:)/.test(path);
}

import { format, isToday, isYesterday } from "date-fns";
import { zhCN } from "date-fns/locale";

/**
 * 获取本周的开始时间（周一的零点）
 * @param date
 */
function getStartOfWeek(date: Date) {
  const day = date.getDay();
  const diff = date.getDate() - day + (day === 0 ? -6 : 1);
  return new Date(date.setDate(diff)).setHours(0, 0, 0, 0);
}

/**
 * 判断是否在同一周
 * @param timestamp
 */
function isSameWeek(timestamp: number) {
  const now = new Date();
  const startOfWeek = getStartOfWeek(new Date(now));
  return timestamp >= startOfWeek;
}

/**
 * 格式化时间
 * @param timestamp
 */
export function formatTime2(timestamp: number) {
  const date = new Date(timestamp);
  if (isToday(date)) {
    return format(date, "aa hh:mm", { locale: zhCN }); // 显示上下午和12小时制的小时分钟，小时补0
  } else if (isYesterday(date)) {
    return `昨天 ${format(date, "aa hh:mm:ss", { locale: zhCN })}`; // 显示昨天
  } else if (isSameWeek(timestamp)) {
    return format(date, "eeee aa hh:mm:ss", { locale: zhCN }); // 显示中文星期几
  } else {
    return format(date, "yyyy-MM-dd aa hh:mm:ss", { locale: zhCN }); // 精确到分钟
  }
}

/**
 * 格式化时间
 * @param timestamp
 * @param formatStr
 */
export function formatTime(timestamp: number, formatStr: string) {
  const date = new Date(timestamp);
  return format(date, formatStr, { locale: zhCN });
}
